
/*
 * Copyright 2002-2021 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2021原作者。
 *
 *根据Apache许可证2.0版（“许可证”）许可；
 *除非符合许可证的规定，否则您不得使用此文件。
 *您可以在以下网址获取许可证副本
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，否则软件
 *根据许可证分发是在“按原样”的基础上分发的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限的特定语言，请参阅许可证
 *许可证下的限制。
 */

package org.springframework.context.support;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.lang.Nullable;
import org.springframework.util.ObjectUtils;

/**
 * Base class for message source implementations, providing support infrastructure
 * such as {@link java.text.MessageFormat} handling but not implementing concrete
 * methods defined in the {@link org.springframework.context.MessageSource}.
 *
 * <p>{@link AbstractMessageSource} derives from this class, providing concrete
 * {@code getMessage} implementations that delegate to a central template
 * method for message code resolution.
 *
 * @author Juergen Hoeller
 * @since 2.5.5
 */
/**
 *用于消息源实现的基类，提供支持基础架构
 *例如{@linkjava.text.MessageFormat}处理但不实现具体
 *在｛@link org.springframework.context.MessageSource｝中定义的方法。
 *
 *＜p＞｛@link AbstractMessageSource｝派生自此类，提供了具体的
 *委托给中心模板的｛@code getMessage｝实现
 *消息代码解析的方法。
 *
 *@作者Juergen Hoeller
 *@自2.5.5起
 */
public abstract class MessageSourceSupport {

	private static final MessageFormat INVALID_MESSAGE_FORMAT = new MessageFormat("");

	/** Logger available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());

	private boolean alwaysUseMessageFormat = false;

	/**
	 * Cache to hold already generated MessageFormats per message.
	 * Used for passed-in default messages. MessageFormats for resolved
	 * codes are cached on a specific basis in subclasses.
	 */
	/** Logger available to subclasses. */
	受保护的最终日志记录器=LogFactory.getLog（getClass（））；

	private布尔值alwaysUseMessageFormat=false；

	/**
	 *缓存以保存每个消息已生成的MessageFormats。
	 *用于传入的默认消息。已解析的消息格式
	 *代码是在特定的基础上缓存在子类中的。
	 */
	private final Map<String, Map<Locale, MessageFormat>> messageFormatsPerMessage = new HashMap<>();


	/**
	 * Set whether to always apply the {@code MessageFormat} rules, parsing even
	 * messages without arguments.
	 * <p>Default is {@code false}: Messages without arguments are by default
	 * returned as-is, without parsing them through {@code MessageFormat}.
	 * Set this to {@code true} to enforce {@code MessageFormat} for all messages,
	 * expecting all message texts to be written with {@code MessageFormat} escaping.
	 * <p>For example, {@code MessageFormat} expects a single quote to be escaped
	 * as two adjacent single quotes ({@code "''"}). If your message texts are all
	 * written with such escaping, even when not defining argument placeholders,
	 * you need to set this flag to {@code true}. Otherwise, only message texts
	 * with actual arguments are supposed to be written with {@code MessageFormat}
	 * escaping.
	 * @see java.text.MessageFormat
	 */
	/**
	 *设置是否始终应用｛@code MessageFormat｝规则，甚至进行解析
	 *没有参数的消息。
	 *＜p＞默认值为｛@code false｝：默认情况下，不带参数的消息
	 *按原样返回，而不通过｛@code MessageFormat｝对其进行解析。
	 *将其设置为｛@code true｝以对所有消息强制执行｛@code-MessageFormat｝，
	 *期望所有消息文本都使用{@code MessageFormat}转义编写。
	 *＜p＞例如，｛@code MessageFormat｝需要转义一个引号
	 *作为两个相邻的单引号（{@code“''”}）。如果你的短信都是
	 *使用这种转义编写，即使在没有定义参数占位符的情况下，
	 *您需要将此标志设置为｛@code true｝。否则，仅显示消息文本
	 *实际参数应该使用｛@code MessageFormat｝编写
	 *逃跑。
	 *@参见java.text.MessageFormat
	 */
	public void setAlwaysUseMessageFormat(boolean alwaysUseMessageFormat) {
		this.alwaysUseMessageFormat = alwaysUseMessageFormat;
	}

	/**
	 * Return whether to always apply the {@code MessageFormat} rules, parsing even
	 * messages without arguments.
	 */
	/**
	 *返回是否始终应用｛@code MessageFormat｝规则，甚至解析
	 *没有参数的消息。
	 */
	protected boolean isAlwaysUseMessageFormat() {
		return this.alwaysUseMessageFormat;
	}


	/**
	 * Render the given default message String. The default message is
	 * passed in as specified by the caller and can be rendered into
	 * a fully formatted default message shown to the user.
	 * <p>The default implementation passes the String to {@code formatMessage},
	 * resolving any argument placeholders found in them. Subclasses may override
	 * this method to plug in custom processing of default messages.
	 * @param defaultMessage the passed-in default message String
	 * @param args array of arguments that will be filled in for params within
	 * the message, or {@code null} if none.
	 * @param locale the Locale used for formatting
	 * @return the rendered default message (with resolved arguments)
	 * @see #formatMessage(String, Object[], java.util.Locale)
	 */
	/**
	 *呈现给定的默认消息字符串。默认消息为
	 *按调用方指定的方式传入，并且可以呈现到
	 *向用户显示完全格式化的默认消息。
	 *＜p＞默认实现将String传递给{@code formatMessage｝，
	 *解析在其中找到的任何参数占位符。子类可以覆盖
	 *这种方法可以插入默认消息的自定义处理。
	 *@param defaultMessage传入的默认消息字符串
	 *@param args将为中的params填充的参数数组
	 *消息，或者｛@code null｝（如果没有）。
	 *@param locale用于格式化的区域设置
	 *@返回呈现的默认消息（带有已解析的参数）
	 *@see#formatMessage（字符串，Object[]，java.util.Locare）
	 */
	protected String renderDefaultMessage(String defaultMessage, @Nullable Object[] args, Locale locale) {
		return formatMessage(defaultMessage, args, locale);
	}

	/**
	 * Format the given message String, using cached MessageFormats.
	 * By default invoked for passed-in default messages, to resolve
	 * any argument placeholders found in them.
	 * @param msg the message to format
	 * @param args array of arguments that will be filled in for params within
	 * the message, or {@code null} if none
	 * @param locale the Locale used for formatting
	 * @return the formatted message (with resolved arguments)
	 */
	/**
	 *使用缓存的MessageFormats设置给定消息字符串的格式。
	 *默认情况下，为传入的默认消息调用，以解决
	 *在其中找到的任何自变量占位符。
	 *@param msg要格式化的消息
	 *@param args将为中的params填充的参数数组
	 *消息，或者｛@code null｝如果没有
	 *@param locale用于格式化的区域设置
	 *@返回格式化的消息（带有已解析的参数）
	 */
	protected String formatMessage(String msg, @Nullable Object[] args, Locale locale) {
		if (!isAlwaysUseMessageFormat() && ObjectUtils.isEmpty(args)) {
			return msg;
		}
		MessageFormat messageFormat = null;
		synchronized (this.messageFormatsPerMessage) {
			Map<Locale, MessageFormat> messageFormatsPerLocale = this.messageFormatsPerMessage.get(msg);
			if (messageFormatsPerLocale != null) {
				messageFormat = messageFormatsPerLocale.get(locale);
			}
			else {
				messageFormatsPerLocale = new HashMap<>();
				this.messageFormatsPerMessage.put(msg, messageFormatsPerLocale);
			}
			if (messageFormat == null) {
				try {
					messageFormat = createMessageFormat(msg, locale);
				}
				catch (IllegalArgumentException ex) {
					// Invalid message format - probably not intended for formatting,
					// 无效的消息格式-可能不是用于格式化的，
					// rather using a message structure with no arguments involved...
					// 而是使用不包含参数的消息结构。。。
					if (isAlwaysUseMessageFormat()) {
						throw ex;
					}
					// Silently proceed with raw message if format not enforced...
					// 如果未强制执行格式，则静默地继续原始消息。。。
					messageFormat = INVALID_MESSAGE_FORMAT;
				}
				messageFormatsPerLocale.put(locale, messageFormat);
			}
		}
		if (messageFormat == INVALID_MESSAGE_FORMAT) {
			return msg;
		}
		synchronized (messageFormat) {
			return messageFormat.format(resolveArguments(args, locale));
		}
	}

	/**
	 * Create a {@code MessageFormat} for the given message and Locale.
	 * @param msg the message to create a {@code MessageFormat} for
	 * @param locale the Locale to create a {@code MessageFormat} for
	 * @return the {@code MessageFormat} instance
	 */
	/**
	 *为给定的消息和区域设置创建｛@code MessageFormat｝。
	 *@param msg要为其创建｛@code MessageFormat｝的消息
	 *@param locale要为其创建｛@code MessageFormat｝的区域设置
	 *@return｛@code MessageFormat｝实例
	 */
	protected MessageFormat createMessageFormat(String msg, Locale locale) {
		return new MessageFormat(msg, locale);
	}

	/**
	 * Template method for resolving argument objects.
	 * <p>The default implementation simply returns the given argument array as-is.
	 * Can be overridden in subclasses in order to resolve special argument types.
	 * @param args the original argument array
	 * @param locale the Locale to resolve against
	 * @return the resolved argument array
	 */
	/**
	 *用于解析参数对象的模板方法。
	 *＜p＞默认实现只是按原样返回给定的参数数组。
	 *可以在子类中重写，以便解析特殊的参数类型。
	 *@param args原始参数数组
	 *@param locale要解析的区域设置
	 *@返回解析的参数数组
	 */
	protected Object[] resolveArguments(@Nullable Object[] args, Locale locale) {
		return (args != null ? args : new Object[0]);
	}

}
